# -*- coding: utf-8 -*-
"""Main Controller"""
from tg import expose, flash, require, url, request, redirect,tmpl_context,validate, config
from pylons.i18n import ugettext as _, lazy_ugettext as l_
#from catwalk.tg2 import Catwalk
from repoze.what import predicates
from formencode import validators,Schema
from lifepyscle.lib.base import BaseController
from lifepyscle.lib.uploader import *
from lifepyscle.model import DBSession, metadata
from lifepyscle.controllers.error import ErrorController
from lifepyscle import model
from lifepyscle.model import *
from lifepyscle.controllers.secure import SecureController
from lifepyscle.widgets import term
term_form = term.term_form
cat="term" # added to every returned dict

class TermController(BaseController):

    @expose('lifepyscle.templates.view_term')
    def index(self, term_id=None,**kw):
        if not term_id:
            flash("Ooops! No term_id provided","error")
            redirect(url('/term/search'))
        else:
            try:
                R = DBSession.query(term).filter(Term.term_id==term_id).one()
            except:
                flash("Ooops! No term exists with term_id %s"%term_id,"warning")
                redirect(url('/term/search'))
            else:
                flash("Found term with term_id %s"%term_id,"ok")
                return dict(cat=cat,page='Term',term=R)

    @expose('lifepyscle.templates.search_term')
    def search(self,**kw):
        return dict(cat=cat,page='Search')

    @expose('json')
    @validate(term_form)
    def add(self,record_id=None,**kw):
        record_id = record_id
        description = kw['description']
        if not kw.has_key('term_type'):
            return dict(add_status=1,msg="You must specify if the term is a right or an obligation",new_term=None,kw=kw)
        term_type = kw['term_type']
        if term_type == 'right': term_type = u'r'
        if term_type == 'obligation': term_type = u'o'
        if not len(description):
            return dict(add_status=1,msg="The term description cannot be left empty",new_term=None,kw=kw)
        if not len(term_type):
            return dict(add_status=1,msg="You must specify if the term is a right or an obligation",new_term=None,kw=kw)
        try:
            R = DBSession.query(Record).filter(Record.record_id==record_id).one()
        except:
            return dict(add_status=1,msg="No Record exists with record_id %s"%record_id,new_term=None,kw=kw)
        else:
            new_term = Term()
            new_term.type = term_type
            new_term.description = description
            R.terms.append(new_term)
            DBSession.flush() # necessary so we can reference the term_id
            tdict = {} # returning an object creates a circular reference
            tdict['record_id'] = record_id
            tdict['description'] = description
            tdict['type'] = term_type
            tdict['achieving'] = new_term.achieving
            tdict['term_id'] = new_term.term_id
            return dict(add_status=0,add_new=tdict,kw=kw,msg="New term added to Record with record_id %s"%record_id)

    @expose('json')
    def delete(self,term_id=None,**kw):
        try:
            T = DBSession.query(Term).filter(Term.term_id==term_id).one()
        except:
            return dict(delete_status=1,msg="No term exists with term_id %s"%term_id)
        else:
            DBSession.delete(T)
            return dict(delete_status=0)

    @expose('json')
    def makeright(self,term_id=None,**kw):
        try:
            T = DBSession.query(Term).filter(Term.term_id==term_id).one()
        except:
            return dict(s=False,d=T.description)
        else:
            T.type = u'r'
            return dict(s=True,d=T.description)

    @expose('json')
    def makeobligation(self,term_id=None,**kw):
        try:
            T = DBSession.query(Term).filter(Term.term_id==term_id).one()
        except:
            return dict(s=False,d=T.description)
        else:
            T.type = u'o'
            return dict(s=True,d=T.description)

    @expose('json')
    def updatedescription(self,id=None,**kw):
        # TODO: fix the script so that it accepts proper json returns (use jeditable's callback) rather than plain strings
        description = kw['value']
        term_id = id.split("_")[0]
        try:
            T = DBSession.query(Term).filter(Term.term_id==term_id).one()
        except:
            #return dict(value=T.description,update_status=1)
            return T.description
        else:
            T.description = description
            #return dict(value=description,update_status=0)
            return description

    @expose('json')
    def markAchieving(self,term_id=None,**kw):
        new_achieving_status = kw['achieving']
        have_term = False
        try:
            T = DBSession.query(Term).filter(Term.term_id==term_id).one()
        except:
            have_term = False
        else:
            have_term = True
            old_achieving_status = T.achieving
            if old_achieving_status:
                old_achieving_status = "yes"
            else:
                old_achieving_status = "no"
        if not have_term:
            return dict(is_achieving="",update_status=1,msg="No term exists with term_id %s"%term_id)
        else:
            if new_achieving_status == 'yes':
                T.achieving = True
            else:
                T.achieving = False
            return dict(is_achieving=new_achieving_status,update_status=0,)
